document.addEventListener('DOMContentLoaded', async function() {
    const customToolsRepository = window.markAnything.customToolsRepository;
    
    // 工具切换功能
    const navItems = document.querySelectorAll('.nav-item');
    const toolPanels = document.querySelectorAll('.tool-panel');
    const customToolsList = document.getElementById('customToolsList');
    const addCustomToolBtn = document.getElementById('addCustomTool');
    const addToolDialog = document.getElementById('addToolDialog');
    const addToolForm = document.getElementById('addToolForm');
    const customToolTemplate = document.getElementById('custom-tool-template');

    // 加载自定义工具
    async function loadCustomTools() {
        const tools = await customToolsRepository.getAllTools();
        customToolsList.innerHTML = '';
        
        tools.forEach(tool => {
            // 添加导航项
            const navItem = document.createElement('button');
            navItem.className = 'nav-item custom-tool-item';
            navItem.dataset.tool = `custom-${tool.id}`;
            navItem.innerHTML = `
                <span class="tool-icon">${tool.icon}</span>
                <span class="tool-name">${tool.name}</span>
            `;
            customToolsList.appendChild(navItem);

            // 创建工具面板
            const panel = customToolTemplate.cloneNode(true);
            panel.id = `custom-${tool.id}-tool`;
            panel.style.display = '';
            panel.querySelector('.custom-tool-name').textContent = tool.name;
            panel.querySelector('.custom-tool-frame').src = tool.url;
            
            // 删除按钮事件
            panel.querySelector('.remove-tool-btn').addEventListener('click', async () => {
                if (confirm('确定要删除这个工具吗？')) {
                    await customToolsRepository.removeTool(tool.id);
                    loadCustomTools();
                    // 如果当前工具被删除，切换到第一个工具
                    if (panel.classList.contains('active')) {
                        document.querySelector('.nav-item').click();
                    }
                }
            });

            document.querySelector('.tools-content').appendChild(panel);
        });

        // 重新绑定导航事件
        bindNavEvents();
    }

    // 绑定导航事件
    function bindNavEvents() {
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', () => {
                const targetTool = item.dataset.tool;
                
                // 更新导航项状态
                document.querySelectorAll('.nav-item').forEach(nav => nav.classList.remove('active'));
                item.classList.add('active');
                
                // 更新工具面板显示
                document.querySelectorAll('.tool-panel').forEach(panel => {
                    if (panel.id === `${targetTool}-tool`) {
                        panel.classList.add('active');
                    } else {
                        panel.classList.remove('active');
                    }
                });
            });
        });
    }

    // 添加自定义工具
    addCustomToolBtn.addEventListener('click', () => {
        addToolDialog.style.display = 'flex';
    });

    // 关闭对话框
    addToolDialog.querySelector('.cancel-btn').addEventListener('click', () => {
        addToolDialog.style.display = 'none';
        addToolForm.reset();
    });

    // 提交表单
    addToolForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const toolName = document.getElementById('toolName').value.trim();
        const toolUrl = document.getElementById('toolUrl').value.trim();

        if (toolName && toolUrl) {
            await customToolsRepository.addTool({
                name: toolName,
                url: toolUrl
            });
            
            addToolDialog.style.display = 'none';
            addToolForm.reset();
            await loadCustomTools();
        }
    });

    // 初始加载自定义工具
    await loadCustomTools();

    // 二维码生成功能
    const urlInput = document.getElementById('urlInput');
    const generateButton = document.getElementById('generateQR');
    const qrResult = document.getElementById('qrResult');
    const downloadButton = document.getElementById('downloadQR');
    const qrColor = document.getElementById('qrColor');
    const qrBgColor = document.getElementById('qrBgColor');
    const qrSize = document.getElementById('qrSize');
    
    let qrcode = null;

    function createQRCode(text) {
        // 清除之前的二维码
        qrResult.innerHTML = '';
        
        // 创建新的二维码
        qrcode = new QRCode(qrResult, {
            text: text,
            width: parseInt(qrSize.value),
            height: parseInt(qrSize.value),
            colorDark: qrColor.value,
            colorLight: qrBgColor.value,
            correctLevel: QRCode.CorrectLevel.H
        });

        // 显示下载按钮
        downloadButton.style.display = 'flex';
    }

    // 生成二维码
    generateButton.addEventListener('click', () => {
        const text = urlInput.value.trim();
        if (text) {
            createQRCode(text);
        }
    });

    // 监听选项变化
    [qrColor, qrBgColor, qrSize].forEach(input => {
        input.addEventListener('change', () => {
            const text = urlInput.value.trim();
            if (text) {
                createQRCode(text);
            }
        });
    });

    // 下载二维码
    downloadButton.addEventListener('click', () => {
        const img = qrResult.querySelector('img');
        if (img) {
            const link = document.createElement('a');
            link.download = 'qrcode.png';
            link.href = img.src;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    });

    // 身份证号生成器功能
    const idCardGenerator = window.markAnything.idCardGenerator;
    const provinceSelect = document.getElementById('province');
    const citySelect = document.getElementById('city');
    const birthDateInput = document.getElementById('birthDate');
    const countInput = document.getElementById('count');
    const idcardForm = document.getElementById('idcardForm');
    const idcardResults = document.querySelector('.idcard-results');
    const idcardList = document.querySelector('.idcard-list');
    const copyButton = document.querySelector('.idcard-copy-btn');
    const exportButton = document.querySelector('.idcard-export-btn');

    // 初始化省份选择器
    function initProvinceSelect() {
        for (const [code, name] of Object.entries(idCardGenerator.provinces)) {
            const option = document.createElement('option');
            option.value = code;
            option.textContent = name;
            provinceSelect.appendChild(option);
        }
    }

    // 更新城市选择器
    function updateCitySelect(provinceCode) {
        citySelect.innerHTML = '<option value="">请选择城市</option>';
        
        const cities = idCardGenerator.cities[provinceCode];
        if (cities) {
            for (const [code, name] of Object.entries(cities)) {
                const option = document.createElement('option');
                option.value = code;
                option.textContent = name;
                citySelect.appendChild(option);
            }
        }
    }

    // 初始化省份选择器
    initProvinceSelect();

    // 监听省份选择变化
    provinceSelect.addEventListener('change', (e) => {
        updateCitySelect(e.target.value);
    });

    // 生成身份证号
    idcardForm.addEventListener('submit', (e) => {
        e.preventDefault();
        
        const provinceCode = provinceSelect.value;
        const cityCode = citySelect.value;
        const birthDate = birthDateInput.value;
        const count = parseInt(countInput.value);

        if (!provinceCode || !cityCode || !birthDate || !count) {
            alert('请填写完整信息');
            return;
        }

        // 生成身份证号
        const idNumbers = idCardGenerator.generateMultiple(provinceCode, cityCode, birthDate, count);

        // 显示结果
        idcardList.innerHTML = '';
        idNumbers.forEach(idNumber => {
            const li = document.createElement('li');
            li.className = 'idcard-item';
            li.textContent = idNumber;
            idcardList.appendChild(li);
        });

        idcardResults.style.display = 'block';
    });

    // 复制全部
    copyButton.addEventListener('click', () => {
        const idNumbers = Array.from(idcardList.children).map(li => li.textContent).join('\n');
        navigator.clipboard.writeText(idNumbers).then(() => {
            alert('已复制到剪贴板');
        });
    });

    // 导出CSV
    exportButton.addEventListener('click', () => {
        const idNumbers = Array.from(idcardList.children).map(li => li.textContent);
        const csvContent = 'data:text/csv;charset=utf-8,' + 
            '身份证号\n' + 
            idNumbers.join('\n');
        
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement('a');
        link.setAttribute('href', encodedUri);
        link.setAttribute('download', '身份证号.csv');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}); 